#!/usr/bin/env python

import LED_Strip_advanced as ledstrip
import time
import random

ledstrip.init()
number = 0
level = 1

class Player(object):
  def __init__(self,name):
    self.name = name
    self.points = 0
    self.lives = 3
  
  def add_point(self):
    self.points = self.points + 1
    
  def get_points(self):
    return self.points
  
  def add_life(self):
    self.lives = self.lives + 1
    
  def take_life(self):
    self.lives = self.lives - 1

  def get_lives(self):
    return self.lives
    
  def get_name(self):
    return self.name

def get_random(number, level):
  # level 1: numbers from 2 to 7
  # level 2: numbers from 4 to 15
  # level 3: numbers from 8 to 31 ...
  new_number = random.randint(2**level,2**(level+2)-1)
  # check that new number is not the same as one turn before
  while (number == new_number):
    new_number = random.randint(2**level,2**(level+2)-1)
  return new_number

def show_number(number, level):
  ledstrip.set_binary(number)
  time.sleep(1+level/2)
  ledstrip.set_binary(0)

def get_level(points):
  # min level=1, max level=6
  return min(6,int(points/5)+1)

def check_guess(number, guess):
  try:
    return number == int(guess)
  except ValueError:
    return False
    
print('****** Welcome to Binary Battle ******')

name = input('\nPlease enter your name: ')
player = Player(name)

print('\n*************** Start ****************\n')

while (player.get_lives()>0):
  number = get_random(number, level)
  show_number(number, level)
  guess = input('What is your guess, ' + player.get_name() + '? ')
  if check_guess(number, guess):
    player.add_point()
    print('Correct! You have ' + str(player.get_points()) + ' points!')
    # statement true, if player has n*5 points
    if get_level(player.get_points()) > get_level(player.get_points()-1):
      player.add_life()
      level = get_level(player.get_points())
      print('New life for ' + player.get_name() + '! ' + str(player.get_lives()) + ' lives left.')
      print('New level is ' + str(level))
  else:
    player.take_life()
    print('False! Number was ' + str(number) + '. You have ' + str(player.get_lives()) + ' lives left.')
  
print('\nGame over... you got ' +  str(player.get_points()) + ' points.')
